"""
用户管理：
1,查询所有用户信息
2,添加分页功能
3,添加过滤功能
4,新增用户功能
"""
from collections import OrderedDict   # OrderedDict有序字典

from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.response import Response

from apps.meiduo_admin.serializers.user import UserSerializer
from apps.users.models import User

from rest_framework.pagination import LimitOffsetPagination, PageNumberPagination

class PageNum(PageNumberPagination):
    # 默认每页几条记录
    page_size = 10
    # 前端要求的数据格式
    page_size_query_param = 'pagesize'
    # 最大数量
    max_page_size = 50

    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),     # 一共多少条数据
            ('lists', data),                          # 结果显示
            ('page', self.page.number),               # 当前页数
            ('pages', self.page.paginator.num_pages), # 一共多少页
            ('pagesize', self.page_size)              # 一页多少条数据
        ]))


class UserListView(ListModelMixin, CreateModelMixin, GenericAPIView):
    # # 获取查询结果集
    # queryset = User.objects.all()

    # 根据需求需要返回不同的查询结果集，就需要重写get_query()方法
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return User.objects.filter(username__contains=keyword)
        else:
            return User.objects.all()


    # 设置序列化器
    serializer_class = UserSerializer

    # 设置分页类
    pagination_class = PageNum

    def get(self, request):
        return self.list(request)

    def post(self, request):
        return self.create(request)

# 三级视图实现查询用户
class UserListAPIView(ListAPIView):
    # 获取查询结果集
    queryset = User.objects.all()
    # 设置序列化器
    serializer_class = UserSerializer